package com.hoshiicloud.mallshop.jobhandler;

import com.hoshiicloud.common.constant.refund.RefundOrderStatusEnum;
import com.hoshiicloud.common.query.OmnipotentWrapper;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.mallshop.feign.ShopSaleOrderFeignService;
import com.hoshiicloud.mallshop.param.UpdateRefundInfoParam;
import com.hoshiicloud.mallshop.service.aftersale.RefundManageService;
import com.hoshiicloud.saleorder.entity.RefundOrder;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.rowset.serial.SerialException;
import java.util.ArrayList;
import java.util.List;

/**
 * 2019/9/4 14:37 qry
 */
@JobHandler("RefundOrderReceiveTimeOutHandler")
@Component
public class RefundOrderReceiveTimeOutHandler extends IJobHandler {
    @Autowired
    private ShopSaleOrderFeignService shopSaleOrderFeignService;
    @Autowired
    private RefundManageService refundManageService;

    @Override
    public ReturnT<String> execute(String s) throws Exception {
        try{
            XxlJobLogger.log("买家已发货，等待商家收货状态超3天自动更新为 商家已收货 任务开始");
            List<OmnipotentWrapper> wrappers = new ArrayList<>();
            wrappers.add(OmnipotentWrapper.setWrapper("eq","status", RefundOrderStatusEnum.WAIT_SELLER_RECEIVE.getCode()));
            wrappers.add(OmnipotentWrapper.setWrapper("ge",
                    "TIMESTAMPDIFF(SECOND,DATE_ADD(create_time,INTERVAL 3 DAY) ,now())", 0));
            Response<List<RefundOrder>> rs1 = shopSaleOrderFeignService.omniRefundOrder(wrappers);
            if(null == rs1 || rs1.getCode() !=200 || null == rs1.getData()){
                XxlJobLogger.log("仅退款且等待商家同意状态超3天自动更新为等待商家打款状态异常：feign调用查询要更新的数据异常");
                throw new SerialException("feign调用查询要更新的数据异常");
            }
            for (RefundOrder ro:rs1.getData()){
                UpdateRefundInfoParam param = new UpdateRefundInfoParam();
                param.setId(ro.getId());
                param.setStatus(RefundOrderStatusEnum.WAIT_SELLER_PAY.getCode());
                try{
                    refundManageService.updateRefundInfo(param);
                }catch (Exception e){
                    XxlJobLogger.log("仅退款且等待商家同意状态超3天自动更新为等待商家打款状态异常,退款单id:"+ro.getId(),e);
                }

            }
            XxlJobLogger.log("买家已发货，等待商家收货状态超3天自动更新为 商家已收货 任务结束");
        }catch (Exception e){
            XxlJobLogger.log("买家已发货，等待商家收货状态超3天自动更新为 商家已收货：",e);
        }
        return SUCCESS;
    }
}
